#pragma once
#include <iostream>
#include <cerrno>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <string>
#include <strings.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>


namespace Client
{
    using namespace std;
    static const std::string defaultIP = "0.0.0.0";
    enum
    {
        USAGE_ERROR = 1,
        SOCK_ERROR,
        BIND_ERROR
    };
    
    class udpclient
    {
    public:
        udpclient(const string &serverip,const uint16_t &serveport)
            :_serverip(serverip),_serverport(serveport), _sockfd(-1),_quit(false)
        {}
        void initClient()
        {
            // 1、socket 套接字操作
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                cerr << "socket error :" << errno << " : " << strerror(errno) << endl;
                exit(SOCK_ERROR);
            }
            cout<<"socket success :"<<_sockfd<<endl;
            //客户端需不需要bind（要想网络通信，肯定需要bind），需不需要明确的bind（不需要）
            //当我们socket之后，os会自动的帮我们随机bind端口号，不需要我们进行操作
        }
        void startClient()
        {
            //对se进行初始化
            memset(&_se,0,sizeof(_se));
            _se.sin_family=AF_INET;
            _se.sin_addr.s_addr=inet_addr(_serverip.c_str());
            _se.sin_port = htons(_serverport);
            string message;
            while(!_quit)
            {
                cout<<"please enter #";
                cin>>message;
                ssize_t num = sendto(_sockfd,message.c_str(),message.size(),0,(sockaddr*)&_se,(socklen_t)sizeof(_se));
                
            }
        }
        ~udpclient()
        {
        }

    private:
        int _sockfd;
        uint16_t _serverport;  //目的port
        string _serverip;      //目的ip
        struct  sockaddr_in _se;
        bool _quit;
    };
}